<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #app {
            position: relative;
        }
    </style>
</head>
<body>
    <div id="app">
        <!-- 自定义指令拖拽一个滑块 -->
        <div v-drag v-color="color" @click="fun"></div>
        <div v-drag v-color="color"></div>
        <div v-drag v-color="color"></div>
    </div>
    <script src="./js/vue.js"></script>
    <script>

        // 自定义指令
        Vue.directive('drag', {
            // bind(el, binding, vnode) {
            //     console.log();
            // },
            inserted(el) {
                el.style.width = '100px'
                el.style.height = '100px'
                el.style.background = 'red'
                el.style.position = 'absolute'
                el.style.left = '10px'
                el.style.top = '10px'
                let startX = 0 // 记录滑块在x轴的位置
                let startY = 0 // 记录滑块在y轴的位置
                // 手机端用touch事件 pc端用点击事件
                el.ontouchstart = function(e) {
                    // console.log(el.offsetLeft, el.offsetTop);
                    startX = e.touches[0].pageX - el.offsetLeft
                    startY = e.touches[0].pageY - el.offsetTop
                    document.ontouchmove = function(mv) {
                        el.style.left = mv.touches[0].pageX - startX + 'px'
                        el.style.top = mv.touches[0].pageY - startY + 'px'
                    }
                }

                document.ontouchend = function() {
                    document.ontouchmove = null
                }

            }
        })

        new Vue({
            el: '#app',
            data: {
                color: 'green'
            },
            directives: {
                color: {
                    inserted(el, b) {
                        // console.log(el, b);
                        el.style.background = b.value
                    },

                    update(el, b) {
                        console.log(el, b);
                        el.style.background = b.value
                    },
                }
            },


            methods: {
                fun() {
                   this.color = 'blue' 
                }
            },
        })
    </script>
</body>
</html>